package com.example.service;

import com.example.bean.Order;
import com.example.bean.OrderItem;
import com.example.bean.Page;
import com.example.dao.OrderDao;
import com.example.util.DBUtil;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * 商品
 */
public class OrderService {

    OrderDao orderDao;

    public OrderService() {
        orderDao = new OrderDao();
    }

    public void saveOrder(Order order) throws SQLException {
        Connection connection = DBUtil.getConnection();
        try {
            connection.setAutoCommit(false); // 关闭自动提交，开始事务

            // 保存订单
            orderDao.saveOrder(connection, order);

            // 保存订单项
            for (OrderItem orderItem : order.getList()) {
                orderDao.saveOrderItem(connection, orderItem);
            }

            // 提交事务
            connection.commit();
        } catch (SQLException e) {
            // 如果出现异常，回滚事务
            connection.rollback();
            throw e;
        } finally {
            DBUtil.close(null, null, connection);  // 确保连接被关闭
        }
    }

    public Order selectOrderByOid(String oid) {
        return orderDao.selectOrderByOid(oid);
    }

    public int updateOrder(Order order) {
        return orderDao.updateOrder(order);
    }

    public Page selectOrderByUid(String id, int pageNo, int pageSize) {
        List<Order> orderList =  orderDao.selectOrderByUid(id, pageNo, pageSize);
        Page page = new Page();
        page.setList(orderList);
        page.setPageNo(pageNo);
        page.setPageSize(pageSize);
        page.setTotalRecords(orderDao.selectOrderCount(id));
        return page;
    }
}